package com.aipartner.controller;

import com.aipartner.common.PageResult;
import com.aipartner.common.Result;
import com.aipartner.dto.*;
import com.aipartner.entity.*;
import com.aipartner.service.*;
import com.aipartner.util.UserContext;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 管理员控制器
 */
@Api(tags = "管理员接口")
@RestController
@RequestMapping("/api/admin")
@Slf4j
public class AdminController {
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CreditsService creditsService;
    
    @Autowired
    private VipService vipService;
    
    @Autowired
    private AiImageService aiImageService;
    
    
    // ==================== 管理员认证接口 ====================
    
    /**
     * 管理员登录
     */
    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody AdminLoginRequest request, HttpServletRequest httpRequest) {
        try {
            String ip = getClientIp(httpRequest);
            LoginResponse response = adminService.login(request, ip);
            return Result.success(response);
        } catch (Exception e) {
            log.error("管理员登录失败", e);
            return Result.fail(e.getMessage());
        }
    }
    
    /**
     * 获取当前管理员信息
     */
    @ApiOperation("获取当前管理员信息")
    @GetMapping("/info")
    public Result<AdminUserResponse> getAdminInfo() {
        try {
            Long adminId = UserContext.getCurrentUserId();
            if (adminId == null) {
                return Result.fail("未登录");
            }
            
            AdminUserResponse adminInfo = adminService.getAdminById(adminId);
            if (adminInfo == null) {
                return Result.fail("管理员不存在");
            }
            
            return Result.success(adminInfo);
        } catch (Exception e) {
            log.error("获取管理员信息失败", e);
            return Result.fail("获取信息失败");
        }
    }
    
    // ==================== 仪表盘接口 ====================
    
    /**
     * 获取仪表盘统计数据
     */
    @ApiOperation("获取仪表盘统计数据")
    @GetMapping("/dashboard/stats")
    public Result<AdminStatsResponse> getDashboardStats() {
        try {
            AdminStatsResponse stats = adminService.getDashboardStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取仪表盘统计数据失败", e);
            return Result.fail("获取统计数据失败");
        }
    }
    
    // ==================== 用户管理接口 ====================
    
    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/users")
    public Result<PageResult<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String vipStatus) {
        try {
            Page<User> page = new Page<>(current, size);
            // 这里需要在UserService中添加管理端查询方法
            page = userService.getAdminUserList(page, userId, nickname, vipStatus);
            
            PageResult<User> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            result.setHasPrevious(page.hasPrevious());
            result.setHasNext(page.hasNext());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.fail("获取用户列表失败");
        }
    }
    
    /**
     * 获取用户详情
     */
    @ApiOperation("获取用户详情")
    @GetMapping("/users/{userId}")
    public Result<User> getUserDetail(@PathVariable Long userId) {
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户详情失败", e);
            return Result.fail("获取用户详情失败");
        }
    }
    
    /**
     * 管理员操作用户积分
     */
    @ApiOperation("管理员操作用户积分")
    @PostMapping("/users/{userId}/credits")
    public Result<Boolean> manageUserCredits(@PathVariable Long userId, @RequestBody Map<String, Object> params) {
        try {
            String type = (String) params.get("type"); // add, subtract, set
            Integer amount = (Integer) params.get("amount");
            String reason = (String) params.get("reason");
            
            if (amount == null || amount <= 0) {
                return Result.fail("积分数量必须大于0");
            }
            
            boolean result = false;
            switch (type) {
                case "add":
                    result = creditsService.addCredits(userId, amount.longValue(), "admin_add", 
                        "ADMIN_" + System.currentTimeMillis(), "管理员添加：" + reason);
                    break;
                case "subtract":
                    result = creditsService.consumeCredits(userId, amount.longValue(), "admin_subtract",
                        "ADMIN_" + System.currentTimeMillis(), "管理员扣减：" + reason);
                    break;
                case "set":
                    result = creditsService.resetUserCredits(userId, amount.longValue());
                    break;
                default:
                    return Result.fail("操作类型错误");
            }
            
            if (result) {
                // 记录操作日志
                logAdminOperation("用户积分管理", "管理用户积分", "用户ID:" + userId + ", 操作:" + type + ", 数量:" + amount);
                return Result.success(true);
            } else {
                return Result.fail("操作失败");
            }
        } catch (Exception e) {
            log.error("管理用户积分失败", e);
            return Result.fail("操作失败：" + e.getMessage());
        }
    }
    
    // ==================== 积分管理接口 ====================
    
    /**
     * 获取积分统计数据
     */
    @ApiOperation("获取积分统计数据")
    @GetMapping("/credits/stats")
    public Result<Map<String, Object>> getCreditsStats() {
        try {
            // 获取积分相关统计数据
            Map<String, Object> stats = creditsService.getAdminCreditsStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取积分统计失败", e);
            return Result.fail("获取统计数据失败");
        }
    }
    
    /**
     * 获取积分套餐列表（管理端，包含所有状态）
     */
    @ApiOperation("获取积分套餐列表")
    @GetMapping("/credits/packages")
    public Result<List<CreditsPackage>> getCreditsPackages() {
        // 强制输出到控制台和日志，确保代码被执行
        System.out.println("=====================================");
        System.out.println("🔥🔥🔥 AdminController.getCreditsPackages() 被调用！！！");
        System.out.println("🔥🔥🔥 时间: " + java.time.LocalDateTime.now());
        System.out.println("=====================================");
        
        try {
            log.error("🎯 [强制日志] AdminController.getCreditsPackages() 被调用");
            log.error("🎯 [强制日志] 完整请求路径: /api/admin/credits/packages");
            log.error("🎯 [强制日志] 调用 creditsService.getAdminCreditsPackages()");
            
            List<CreditsPackage> packages = creditsService.getAdminCreditsPackages();
            
            System.out.println("🔥🔥🔥 获取到套餐数量: " + packages.size());
            log.error("🎯 [强制日志] 管理端获取套餐列表完成，共{}个套餐", packages.size());
            
            if (!packages.isEmpty()) {
                System.out.println("🔥🔥🔥 第一个套餐: " + packages.get(0).getName());
                log.error("🎯 [强制日志] 第一个套餐: {} (状态: {})", packages.get(0).getName(), packages.get(0).getStatus());
            }
            
            return Result.success(packages);
        } catch (Exception e) {
            System.out.println("🔥🔥🔥 发生错误: " + e.getMessage());
            log.error("🎯 [强制日志] AdminController 获取积分套餐失败", e);
            return Result.fail("获取套餐列表失败");
        }
    }
    
    /**
     * 创建积分套餐
     */
    @ApiOperation("创建积分套餐")
    @PostMapping("/credits/packages")
    public Result<Boolean> createCreditsPackage(@RequestBody CreditsPackage creditsPackage) {
        try {
            log.info("管理员请求创建积分套餐: {}", creditsPackage.getName());
            boolean result = creditsService.createCreditsPackage(creditsPackage);
            if (result) {
                log.info("积分套餐创建成功: {}", creditsPackage.getName());
                logAdminOperation("积分管理", "创建积分套餐", "套餐名称:" + creditsPackage.getName());
                return Result.success(true);
            } else {
                log.warn("积分套餐创建失败: {}", creditsPackage.getName());
                return Result.fail("创建失败");
            }
        } catch (Exception e) {
            log.error("创建积分套餐失败: {}", creditsPackage.getName(), e);
            return Result.fail("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新积分套餐
     */
    @ApiOperation("更新积分套餐")
    @PutMapping("/credits/packages/{id}")
    public Result<Boolean> updateCreditsPackage(@PathVariable Long id, @RequestBody CreditsPackage creditsPackage) {
        // 强制输出到控制台，确保代码被执行
        System.out.println("=====================================");
        System.out.println("🔥🔥🔥 AdminController.updateCreditsPackage() 被调用！！！");
        System.out.println("🔥🔥🔥 套餐ID: " + id);
        System.out.println("🔥🔥🔥 新数据: " + creditsPackage);
        System.out.println("=====================================");
        
        try {
            log.error("🎯 [编辑调试] 管理员请求更新积分套餐: ID={}, 新名称={}", id, creditsPackage.getName());
            log.error("🎯 [编辑调试] 套餐数据: 积分={}, 价格={}, 状态={}", 
                creditsPackage.getCreditsAmount(), creditsPackage.getPrice(), creditsPackage.getStatus());
            
            boolean result = creditsService.updateCreditsPackage(id, creditsPackage);
            
            System.out.println("🔥🔥🔥 Service返回结果: " + result);
            
            if (result) {
                log.error("🎯 [编辑调试] 积分套餐更新成功: ID={}", id);
                logAdminOperation("积分管理", "更新积分套餐", "套餐ID:" + id + ", 名称:" + creditsPackage.getName());
                return Result.success(true);
            } else {
                log.error("🎯 [编辑调试] 积分套餐更新失败: ID={}", id);
                return Result.fail("更新失败");
            }
        } catch (Exception e) {
            System.out.println("🔥🔥🔥 发生异常: " + e.getMessage());
            log.error("🎯 [编辑调试] 更新积分套餐异常: ID={}", id, e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除积分套餐
     */
    @ApiOperation("删除积分套餐")
    @DeleteMapping("/credits/packages/{id}")
    public Result<Boolean> deleteCreditsPackage(@PathVariable Long id) {
        try {
            boolean result = creditsService.deleteCreditsPackage(id);
            if (result) {
                logAdminOperation("积分管理", "删除积分套餐", "套餐ID:" + id);
                return Result.success(true);
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除积分套餐失败", e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新积分套餐状态
     */
    @ApiOperation("更新积分套餐状态")
    @PutMapping("/credits/packages/{id}/status")
    public Result<Boolean> updateCreditsPackageStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            Integer status = (Integer) params.get("status");
            String action = status == 1 ? "上架" : "下架";
            log.info("管理员请求{}积分套餐: ID={}, 状态={}", action, id, status);
            
            boolean result = creditsService.updateCreditsPackageStatus(id, status);
            if (result) {
                log.info("积分套餐{}成功: ID={}", action, id);
                logAdminOperation("积分管理", action + "积分套餐", "套餐ID:" + id);
                return Result.success(true);
            } else {
                log.warn("积分套餐{}失败: ID={}", action, id);
                return Result.fail("操作失败");
            }
        } catch (Exception e) {
            log.error("更新积分套餐状态失败: ID={}", id, e);
            return Result.fail("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取积分交易记录
     */
    @ApiOperation("获取积分交易记录")
    @GetMapping("/credits/transactions")
    public Result<PageResult<CreditsTransaction>> getCreditsTransactions(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String transactionType) {
        try {
            Page<CreditsTransaction> page = new Page<>(current, size);
            page = creditsService.getAdminCreditsHistory(page, userId, transactionType);
            
            PageResult<CreditsTransaction> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取积分交易记录失败", e);
            return Result.fail("获取交易记录失败");
        }
    }
    
    /**
     * 获取积分消耗规则（管理端，包含所有状态）
     */
    @ApiOperation("获取积分消耗规则")
    @GetMapping("/credits/rules")
    public Result<List<Map<String, Object>>> getCreditsRules() {
        try {
            List<Map<String, Object>> rules = creditsService.getAllCreditsRules();
            return Result.success(rules);
        } catch (Exception e) {
            log.error("获取积分消耗规则失败", e);
            return Result.fail("获取消耗规则失败");
        }
    }
    
    /**
     * 创建积分消耗规则
     */
    @ApiOperation("创建积分消耗规则")
    @PostMapping("/credits/rules")
    public Result<Boolean> createCreditsRule(@RequestBody Map<String, Object> params) {
        try {
            String type = (String) params.get("type");
            String name = (String) params.get("name");
            Long cost = Long.valueOf(params.get("cost").toString());
            String unit = (String) params.get("unit");
            String description = (String) params.get("description");
            
            boolean result = creditsService.createCreditsRule(type, name, cost, unit, description);
            if (result) {
                logAdminOperation("积分管理", "创建积分消耗规则", "规则名称:" + name);
                return Result.success(true);
            } else {
                return Result.fail("创建失败");
            }
        } catch (Exception e) {
            log.error("创建积分消耗规则失败", e);
            return Result.fail("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新积分消耗规则
     */
    @ApiOperation("更新积分消耗规则")
    @PutMapping("/credits/rules/{id}")
    public Result<Boolean> updateCreditsRule(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            String type = (String) params.get("type");
            String name = (String) params.get("name");
            Long cost = Long.valueOf(params.get("cost").toString());
            String unit = (String) params.get("unit");
            String description = (String) params.get("description");
            
            boolean result = creditsService.updateCreditsRule(id, type, name, cost, unit, description);
            if (result) {
                logAdminOperation("积分管理", "更新积分消耗规则", "规则ID:" + id);
                return Result.success(true);
            } else {
                return Result.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新积分消耗规则失败", e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除积分消耗规则
     */
    @ApiOperation("删除积分消耗规则")
    @DeleteMapping("/credits/rules/{id}")
    public Result<Boolean> deleteCreditsRule(@PathVariable Long id) {
        try {
            boolean result = creditsService.deleteCreditsRule(id);
            if (result) {
                logAdminOperation("积分管理", "删除积分消耗规则", "规则ID:" + id);
                return Result.success(true);
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除积分消耗规则失败", e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新积分消耗规则状态
     */
    @ApiOperation("更新积分消耗规则状态")
    @PutMapping("/credits/rules/{id}/status")
    public Result<Boolean> updateCreditsRuleStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            Integer status = (Integer) params.get("status");
            boolean result = creditsService.updateCreditsRuleStatus(id, status);
            if (result) {
                String action = status == 1 ? "启用" : "禁用";
                logAdminOperation("积分管理", action + "积分消耗规则", "规则ID:" + id);
                return Result.success(true);
            } else {
                return Result.fail("操作失败");
            }
        } catch (Exception e) {
            log.error("更新积分消耗规则状态失败", e);
            return Result.fail("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 同步积分套餐到小程序数据库
     */
    @ApiOperation("同步积分套餐到小程序数据库")
    @PostMapping("/credits/packages/sync")
    public Result<Boolean> syncCreditsPackagesToMiniProgram() {
        try {
            boolean result = creditsService.syncCreditsPackagesToMiniProgram();
            if (result) {
                logAdminOperation("积分管理", "同步积分套餐", "同步到小程序数据库");
                return Result.success(true);
            } else {
                return Result.fail("同步失败");
            }
        } catch (Exception e) {
            log.error("同步积分套餐失败", e);
            return Result.fail("同步失败：" + e.getMessage());
        }
    }
    
    /**
     * 同步积分消耗规则到小程序数据库
     */
    @ApiOperation("同步积分消耗规则到小程序数据库")
    @PostMapping("/credits/rules/sync")
    public Result<Boolean> syncCreditsRulesToMiniProgram() {
        try {
            boolean result = creditsService.syncCreditsRulesToMiniProgram();
            if (result) {
                logAdminOperation("积分管理", "同步积分消耗规则", "同步到小程序数据库");
                return Result.success(true);
            } else {
                return Result.fail("同步失败");
            }
        } catch (Exception e) {
            log.error("同步积分消耗规则失败", e);
            return Result.fail("同步失败：" + e.getMessage());
        }
    }
    
    // ==================== 订单管理接口 ====================
    
    /**
     * 获取订单统计数据
     */
    @ApiOperation("获取订单统计数据")
    @GetMapping("/orders/stats")
    public Result<Map<String, Object>> getOrderStats() {
        try {
            Map<String, Object> stats = creditsService.getAdminOrderStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取订单统计失败", e);
            return Result.fail("获取统计数据失败");
        }
    }
    
    /**
     * 获取订单列表
     */
    @ApiOperation("获取订单列表")
    @GetMapping("/orders")
    public Result<PageResult<CreditsOrder>> getOrderList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String orderType,
            @RequestParam(required = false) String status) {
        try {
            Page<CreditsOrder> page = new Page<>(current, size);
            page = creditsService.getAdminOrderList(page, orderNo, userId, orderType, status);
            
            PageResult<CreditsOrder> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return Result.fail("获取订单列表失败");
        }
    }
    
    /**
     * 取消订单
     */
    @ApiOperation("取消订单")
    @PutMapping("/orders/{orderId}/cancel")
    public Result<Boolean> cancelOrder(@PathVariable Long orderId) {
        try {
            boolean result = creditsService.cancelOrder(orderId);
            if (result) {
                // 记录操作日志
                logAdminOperation("订单管理", "取消订单", "订单ID:" + orderId);
                return Result.success(true);
            } else {
                return Result.fail("取消订单失败，请检查订单状态");
            }
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return Result.fail("取消订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 退款订单
     */
    @ApiOperation("退款订单")
    @PutMapping("/orders/{orderId}/refund")
    public Result<Boolean> refundOrder(@PathVariable Long orderId, @RequestBody Map<String, Object> params) {
        try {
            String reason = (String) params.get("reason");
            Object amountObj = params.get("amount");
            
            if (amountObj == null) {
                return Result.fail("退款金额不能为空");
            }
            
            BigDecimal refundAmount;
            try {
                refundAmount = new BigDecimal(amountObj.toString());
            } catch (NumberFormatException e) {
                return Result.fail("退款金额格式不正确");
            }
            
            boolean result = creditsService.refundOrder(orderId, reason, refundAmount);
            if (result) {
                // 记录操作日志
                logAdminOperation("订单管理", "订单退款", 
                    "订单ID:" + orderId + ", 退款金额:" + refundAmount + ", 原因:" + reason);
                return Result.success(true);
            } else {
                return Result.fail("退款失败，请检查订单状态和退款金额");
            }
        } catch (Exception e) {
            log.error("订单退款失败", e);
            return Result.fail("订单退款失败：" + e.getMessage());
        }
    }
    
    // ==================== 系统管理接口 ====================
    
    /**
     * 获取操作日志
     */
    @ApiOperation("获取操作日志")
    @GetMapping("/system/logs")
    public Result<PageResult<AdminOperationLog>> getOperationLogs(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) Long adminId,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String operation) {
        try {
            Page<AdminOperationLog> page = new Page<>(current, size);
            page = adminService.getOperationLogs(page, adminId, module, operation);
            
            PageResult<AdminOperationLog> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取操作日志失败", e);
            return Result.fail("获取操作日志失败");
        }
    }
    
    // ==================== VIP管理接口 ====================
    
    /**
     * 获取VIP统计数据
     */
    @ApiOperation("获取VIP统计数据")
    @GetMapping("/vip/stats")
    public Result<Map<String, Object>> getVipStats() {
        try {
            Map<String, Object> stats = vipService.getAdminVipStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取VIP统计数据失败", e);
            return Result.fail("获取VIP统计数据失败");
        }
    }
    
    /**
     * 获取VIP用户列表
     */
    @ApiOperation("获取VIP用户列表")
    @GetMapping("/vip/users")
    public Result<PageResult<User>> getVipUsers(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String level) {
        try {
            Page<User> page = new Page<>(current, size);
            page = vipService.getAdminVipUsers(page, keyword, status, level);
            
            PageResult<User> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取VIP用户列表失败", e);
            return Result.fail("获取VIP用户列表失败");
        }
    }
    
    /**
     * VIP用户续期
     */
    @ApiOperation("VIP用户续期")
    @PostMapping("/vip/users/{userId}/extend")
    public Result<Boolean> extendVipUser(@PathVariable Long userId, @RequestBody Map<String, Object> params) {
        try {
            Integer duration = (Integer) params.get("duration");
            String durationType = (String) params.get("durationType");
            
            if (duration == null || duration <= 0) {
                return Result.fail("续期时长必须大于0");
            }
            
            boolean result = vipService.extendVipUser(userId, duration, durationType);
            if (result) {
                logAdminOperation("VIP管理", "用户续期", "用户ID:" + userId + ", 续期:" + duration + durationType);
                return Result.success(true);
            } else {
                return Result.fail("续期失败");
            }
        } catch (Exception e) {
            log.error("VIP用户续期失败", e);
            return Result.fail("续期失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消用户VIP
     */
    @ApiOperation("取消用户VIP")
    @PostMapping("/vip/users/{userId}/cancel")
    public Result<Boolean> cancelUserVip(@PathVariable Long userId, @RequestBody Map<String, Object> params) {
        try {
            String reason = (String) params.get("reason");
            
            boolean result = vipService.cancelUserVip(userId, reason);
            if (result) {
                logAdminOperation("VIP管理", "取消VIP", "用户ID:" + userId + ", 原因:" + reason);
                return Result.success(true);
            } else {
                return Result.fail("取消VIP失败");
            }
        } catch (Exception e) {
            log.error("取消用户VIP失败", e);
            return Result.fail("取消VIP失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取VIP套餐列表（管理端）
     */
    @ApiOperation("获取VIP套餐列表（管理端）")
    @GetMapping("/vip/packages")
    public Result<List<VipPlanResponse>> getVipPackages() {
        try {
            List<VipPlanResponse> packages = vipService.getAdminVipPackages();
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取VIP套餐列表失败", e);
            return Result.fail("获取VIP套餐列表失败");
        }
    }
    
    /**
     * 更新VIP套餐状态
     */
    @ApiOperation("更新VIP套餐状态")
    @PutMapping("/vip/packages/{id}/status")
    public Result<Boolean> updateVipPackageStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            Integer status = (Integer) params.get("status");
            
            boolean result = vipService.updateVipPackageStatus(id, status);
            if (result) {
                String statusText = status == 1 ? "启用" : "禁用";
                logAdminOperation("VIP管理", "套餐状态更新", "套餐ID:" + id + ", 状态:" + statusText);
                return Result.success(true);
            } else {
                return Result.fail("状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新VIP套餐状态失败", e);
            return Result.fail("状态更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除VIP套餐
     */
    @ApiOperation("删除VIP套餐")
    @DeleteMapping("/vip/packages/{id}")
    public Result<Boolean> deleteVipPackage(@PathVariable Long id) {
        try {
            boolean result = vipService.deleteVipPackage(id);
            if (result) {
                logAdminOperation("VIP管理", "删除套餐", "套餐ID:" + id);
                return Result.success(true);
            } else {
                return Result.fail("删除套餐失败");
            }
        } catch (Exception e) {
            log.error("删除VIP套餐失败", e);
            return Result.fail("删除套餐失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建VIP套餐
     */
    @ApiOperation("创建VIP套餐")
    @PostMapping("/vip/packages")
    public Result<Boolean> createVipPackage(@Valid @RequestBody VipPackageRequest request) {
        try {
            boolean result = vipService.createVipPackage(request);
            if (result) {
                logAdminOperation("VIP管理", "创建套餐", "套餐类型:" + request.getType() + ", 名称:" + request.getName());
                return Result.success(true);
            } else {
                return Result.fail("创建套餐失败，可能套餐类型已存在");
            }
        } catch (Exception e) {
            log.error("创建VIP套餐失败", e);
            return Result.fail("创建套餐失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新VIP套餐
     */
    @ApiOperation("更新VIP套餐")
    @PutMapping("/vip/packages/{id}")
    public Result<Boolean> updateVipPackage(@PathVariable Long id, @Valid @RequestBody VipPackageRequest request) {
        try {
            boolean result = vipService.updateVipPackage(id, request);
            if (result) {
                logAdminOperation("VIP管理", "更新套餐", "套餐ID:" + id + ", 套餐类型:" + request.getType() + ", 名称:" + request.getName());
                return Result.success(true);
            } else {
                return Result.fail("更新套餐失败，可能套餐不存在或类型重复");
            }
        } catch (Exception e) {
            log.error("更新VIP套餐失败", e);
            return Result.fail("更新套餐失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取VIP订单列表
     */
    @ApiOperation("获取VIP订单列表")
    @GetMapping("/vip/orders")
    public Result<PageResult<VipOrder>> getVipOrders(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status) {
        try {
            Page<VipOrder> page = new Page<>(current, size);
            page = vipService.getAdminVipOrders(page, keyword, status);
            
            PageResult<VipOrder> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取VIP订单列表失败", e);
            return Result.fail("获取VIP订单列表失败");
        }
    }
    
    /**
     * VIP订单退款
     */
    @ApiOperation("VIP订单退款")
    @PostMapping("/vip/orders/{orderNo}/refund")
    public Result<Boolean> refundVipOrder(@PathVariable String orderNo, @RequestBody Map<String, Object> params) {
        try {
            String reason = (String) params.get("reason");
            BigDecimal amount = null;
            if (params.get("amount") != null) {
                amount = new BigDecimal(params.get("amount").toString());
            }
            
            boolean result = vipService.refundVipOrder(orderNo, reason, amount);
            if (result) {
                logAdminOperation("VIP管理", "订单退款", "订单号:" + orderNo + ", 原因:" + reason);
                return Result.success(true);
            } else {
                return Result.fail("订单退款失败");
            }
        } catch (Exception e) {
            log.error("VIP订单退款失败", e);
            return Result.fail("订单退款失败：" + e.getMessage());
        }
    }
    
    // ==================== AI生图统计接口 ====================
    
    /**
     * 获取AI生图统计数据
     */
    @ApiOperation("获取AI生图统计数据")
    @GetMapping("/ai-image/stats")
    public Result<Map<String, Object>> getAiImageStats() {
        try {
            log.info("管理员请求AI生图统计数据");
            Map<String, Object> stats = aiImageService.getAdminAiImageStats();
            log.info("返回AI生图统计数据: {}", stats);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取AI生图统计数据失败", e);
            return Result.fail("获取AI生图统计数据失败: " + e.getMessage());
        }
    }
    

    /**
     * 获取AI生图历史记录（管理端）
     */
    @ApiOperation("获取AI生图历史记录")
    @GetMapping("/ai-image/history")
    public Result<PageResult<AiImageHistory>> getAiImageHistory(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status) {
        try {
            log.info("=== AI生图历史记录请求开始 ===");
            log.info("接收到的参数: current={}, size={}, keyword={}, status={}", 
                    current, size, keyword, status);
            log.info("参数类型: current={}, size={}", current.getClass().getSimpleName(), size.getClass().getSimpleName());
            
            Page<AiImageHistory> page = new Page<>(current, size);
            log.info("创建分页对象: current={}, size={}", page.getCurrent(), page.getSize());
            log.info("分页对象值: current={}, size={}", page.getCurrent(), page.getSize());
            
            Page<AiImageHistory> beforeService = new Page<>(page.getCurrent(), page.getSize());
            log.info("调用Service前的分页对象: current={}, size={}", beforeService.getCurrent(), beforeService.getSize());
            
            page = aiImageService.getAdminAiImageHistory(page, keyword, status);
            log.info("Service返回后的分页对象: current={}, size={}, total={}, pages={}, records={}", 
                    page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), page.getRecords().size());
            
            PageResult<AiImageHistory> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            result.setHasPrevious(page.hasPrevious());
            result.setHasNext(page.hasNext());
            
            log.info("构建PageResult: current={}, size={}, total={}, pages={}, hasNext={}, hasPrevious={}", 
                    result.getCurrent(), result.getSize(), result.getTotal(), result.getPages(), 
                    result.getHasNext(), result.getHasPrevious());
            log.info("=== AI生图历史记录请求完成 ===");
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取AI生图历史记录失败", e);
            return Result.fail("获取AI生图历史记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除AI生图记录（管理端）
     */
    @ApiOperation("删除AI生图记录")
    @DeleteMapping("/ai-image/history/{recordId}")
    public Result<Boolean> deleteAiImageRecord(@PathVariable String recordId) {
        try {
            log.info("管理员删除AI生图记录请求: recordId={}", recordId);
            
            if (recordId == null || recordId.trim().isEmpty()) {
                return Result.fail("记录ID不能为空");
            }
            
            // 将字符串ID转换为Long类型
            Long recordIdLong;
            try {
                recordIdLong = Long.parseLong(recordId.trim());
            } catch (NumberFormatException e) {
                log.warn("无效的记录ID格式: recordId={}", recordId);
                return Result.fail("记录ID格式不正确");
            }
            
            if (recordIdLong <= 0) {
                return Result.fail("记录ID必须大于0");
            }
            
            boolean success = aiImageService.adminDeleteAiImageRecord(recordIdLong);
            
            if (success) {
                // 记录管理员操作日志
                logAdminOperation("AI生图管理", "删除记录", "记录ID: " + recordIdLong);
                log.info("管理员成功删除AI生图记录: recordId={}", recordIdLong);
                return Result.success(true);
            } else {
                log.warn("删除AI生图记录失败，记录可能不存在: recordId={}", recordIdLong);
                return Result.fail("删除失败，记录可能不存在");
            }
        } catch (Exception e) {
            log.error("删除AI生图记录失败: recordId={}", recordId, e);
            return Result.fail("删除失败: " + e.getMessage());
        }
    }
    
    // ==================== 头像文件服务 ====================
    
    /**
     * 直接提供头像文件服务
     */
    @ApiOperation("获取头像文件")
    @GetMapping("/avatars/{filename}")
    public void getAvatar(@PathVariable String filename, HttpServletResponse response) {
        try {
            String projectRoot = System.getProperty("user.dir");
            File avatarFile = new File(projectRoot, "uploads/avatars/" + filename);
            
            log.info("请求头像文件: {}", avatarFile.getAbsolutePath());
            
            if (!avatarFile.exists()) {
                log.error("头像文件不存在: {}", avatarFile.getAbsolutePath());
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            
            // 设置响应头
            response.setContentType("image/jpeg");
            response.setContentLength((int) avatarFile.length());
            response.setHeader("Cache-Control", "no-cache");
            
            // 读取文件并写入响应
            try (FileInputStream fis = new FileInputStream(avatarFile);
                 OutputStream os = response.getOutputStream()) {
                
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
                os.flush();
            }
            
        } catch (IOException e) {
            log.error("读取头像文件失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    
    // ==================== 工具方法 ====================
    
    /**
     * 获取客户端IP
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip != null && ip.contains(",") ? ip.split(",")[0].trim() : ip;
    }
    
    /**
     * 记录管理员操作日志
     */
    private void logAdminOperation(String module, String operation, String description) {
        try {
            Long adminId = UserContext.getCurrentUserId();
            if (adminId != null) {
                AdminOperationLog log = new AdminOperationLog();
                log.setAdminId(adminId);
                log.setAdminName("管理员"); // 这里可以从上下文获取具体名称
                log.setModule(module);
                log.setOperation(operation);
                log.setDescription(description);
                log.setStatus(1);
                
                adminService.saveOperationLog(log);
            }
        } catch (Exception e) {
            log.error("记录操作日志失败", e);
        }
    }
    
    // ==================== 用户作品管理接口 ====================
    
    /**
     * 获取用户作品列表（管理端）
     */
    @ApiOperation("获取用户作品列表")
    @GetMapping("/user-works")
    public Result<PageResult<UserWork>> getUserWorkList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String isPublic) {
        try {
            log.info("=== 管理端用户作品列表请求开始 ===");
            log.info("接收到的参数: current={}, size={}, keyword={}, status={}, isPublic={}", 
                    current, size, keyword, status, isPublic);
            
            Page<UserWork> page = new Page<>(current, size);
            page = aiImageService.getAdminUserWorkList(page, keyword, status, isPublic);
            
            PageResult<UserWork> result = new PageResult<>();
            result.setData(page.getRecords());
            result.setTotal(page.getTotal());
            result.setCurrent((int) page.getCurrent());
            result.setSize((int) page.getSize());
            result.setPages(page.getPages());
            result.setHasPrevious(page.hasPrevious());
            result.setHasNext(page.hasNext());
            
            log.info("构建用户作品PageResult: current={}, size={}, total={}, pages={}, hasNext={}, hasPrevious={}", 
                    result.getCurrent(), result.getSize(), result.getTotal(), result.getPages(), 
                    result.getHasNext(), result.getHasPrevious());
            log.info("=== 管理端用户作品列表请求完成 ===");
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户作品列表失败", e);
            return Result.fail("获取用户作品列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除用户作品（管理端）
     */
    @ApiOperation("删除用户作品")
    @DeleteMapping("/user-works/{workId}")
    public Result<Boolean> deleteUserWork(@PathVariable String workId) {
        try {
            log.info("管理员删除用户作品请求: workId={}", workId);
            
            if (workId == null || workId.trim().isEmpty()) {
                return Result.fail("作品ID不能为空");
            }
            
            // 将字符串ID转换为Long类型
            Long workIdLong;
            try {
                workIdLong = Long.parseLong(workId.trim());
            } catch (NumberFormatException e) {
                log.warn("无效的作品ID格式: workId={}", workId);
                return Result.fail("作品ID格式不正确");
            }
            
            if (workIdLong <= 0) {
                return Result.fail("作品ID必须大于0");
            }
            
            boolean success = aiImageService.adminDeleteUserWork(workIdLong);
            
            if (success) {
                // 记录管理员操作日志
                logAdminOperation("用户作品管理", "删除作品", "作品ID: " + workIdLong);
                log.info("管理员成功删除用户作品: workId={}", workIdLong);
                return Result.success(true);
            } else {
                log.warn("删除用户作品失败，作品可能不存在: workId={}", workIdLong);
                return Result.fail("删除失败，作品可能不存在");
            }
        } catch (Exception e) {
            log.error("删除用户作品失败: workId={}", workId, e);
            return Result.fail("删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户作品统计数据
     */
    @ApiOperation("获取用户作品统计数据")
    @GetMapping("/user-works/stats")
    public Result<Map<String, Object>> getUserWorkStats() {
        try {
            log.info("管理员请求用户作品统计数据");
            Map<String, Object> stats = aiImageService.getAdminUserWorkStats();
            log.info("返回用户作品统计数据: {}", stats);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户作品统计数据失败", e);
            return Result.fail("获取用户作品统计数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户作品状态（隐藏/显示）
     */
    @ApiOperation("更新用户作品状态")
    @PutMapping("/user-works/{workId}/status")
    public Result<Boolean> updateUserWorkStatus(@PathVariable String workId, @RequestBody Map<String, Object> params) {
        try {
            log.info("管理员更新用户作品状态请求: workId={}, params={}", workId, params);
            
            if (workId == null || workId.trim().isEmpty()) {
                return Result.fail("作品ID不能为空");
            }
            
            Long workIdLong;
            try {
                workIdLong = Long.parseLong(workId.trim());
            } catch (NumberFormatException e) {
                log.warn("无效的作品ID格式: workId={}", workId);
                return Result.fail("作品ID格式不正确");
            }
            
            Integer status = (Integer) params.get("status");
            if (status == null || (status != 0 && status != 1)) {
                return Result.fail("状态参数错误，只能是0（隐藏）或1（显示）");
            }
            
            boolean success = aiImageService.adminUpdateUserWorkStatus(workIdLong, status);
            
            if (success) {
                String statusText = status == 1 ? "显示" : "隐藏";
                logAdminOperation("用户作品管理", "更新状态", "作品ID: " + workIdLong + ", 状态: " + statusText);
                log.info("管理员成功更新用户作品状态: workId={}, status={}", workIdLong, status);
                return Result.success(true);
            } else {
                log.warn("更新用户作品状态失败，作品可能不存在: workId={}", workIdLong);
                return Result.fail("更新失败，作品可能不存在");
            }
        } catch (Exception e) {
            log.error("更新用户作品状态失败: workId={}", workId, e);
            return Result.fail("更新失败: " + e.getMessage());
        }
    }
    
    // ==================== 个人信息管理接口 ====================
    
    /**
     * 获取个人信息
     */
    @ApiOperation("获取个人信息")
    @GetMapping("/profile")
    public Result<AdminUser> getProfile() {
        try {
            Long adminId = UserContext.getCurrentUserId();
            if (adminId == null) {
                return Result.fail("未登录");
            }
            
            AdminUser profile = adminService.getProfile(adminId);
            if (profile != null) {
                // 清除密码字段
                profile.setPassword(null);
            }
            
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取个人信息失败", e);
            return Result.fail("获取个人信息失败");
        }
    }
    
    /**
     * 更新个人信息
     */
    @ApiOperation("更新个人信息")
    @PutMapping("/profile")
    public Result<Void> updateProfile(@RequestBody @Valid AdminProfileRequest request) {
        try {
            Long adminId = UserContext.getCurrentUserId();
            if (adminId == null) {
                return Result.fail("未登录");
            }
            
            boolean success = adminService.updateProfile(adminId, request);
            if (success) {
                logAdminOperation("个人信息管理", "更新个人信息", "更新个人信息");
                return Result.success();
            } else {
                return Result.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新个人信息失败", e);
            return Result.fail("更新失败");
        }
    }
    
    /**
     * 修改密码
     */
    @ApiOperation("修改密码")
    @PutMapping("/profile/password")
    public Result<Void> updatePassword(@RequestBody @Valid AdminPasswordRequest request) {
        try {
            Long adminId = UserContext.getCurrentUserId();
            if (adminId == null) {
                return Result.fail("未登录");
            }
            
            boolean success = adminService.updatePassword(adminId, request);
            if (success) {
                logAdminOperation("个人信息管理", "修改密码", "修改密码");
                return Result.success();
            } else {
                return Result.fail("密码修改失败");
            }
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.fail(e.getMessage());
        }
    }
    
    /**
     * 上传头像
     */
    @ApiOperation("上传头像")
    @PostMapping("/profile/avatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            Long adminId = UserContext.getCurrentUserId();
            if (adminId == null) {
                return Result.fail("未登录");
            }
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.fail("文件不能为空");
            }
            
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.fail("只能上传图片文件");
            }
            
            if (file.getSize() > 2 * 1024 * 1024) { // 2MB
                return Result.fail("文件大小不能超过2MB");
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = "avatar_" + adminId + "_" + System.currentTimeMillis() + extension;
            
            // 保存文件到项目根目录下的uploads/avatars目录
            String projectRoot = System.getProperty("user.dir");
            java.io.File uploadDir = new java.io.File(projectRoot, "uploads/avatars");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            java.io.File destFile = new java.io.File(uploadDir, fileName);
            file.transferTo(destFile);
            
            String avatarUrl = "/uploads/avatars/" + fileName;
            
            // 更新管理员头像
            boolean success = adminService.updateAvatar(adminId, avatarUrl);
            if (success) {
                Map<String, String> result = new HashMap<>();
                result.put("url", avatarUrl);
                
                logAdminOperation("个人信息管理", "更新头像", "更新头像");
                return Result.success(result);
            } else {
                return Result.fail("头像上传失败");
            }
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return Result.fail("上传失败");
        }
    }
}
